using micromsg;
using MicroMsg.Common.Event;
using MicroMsg.Common.Utils;
using MicroMsg.Manager;
using MicroMsg.Network;
using MicroMsg.Protocol;
using MicroMsg.Storage;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
namespace MicroMsg.Scene.Image
{
	public class NetSceneUploadImage : NetSceneBaseEx<UploadMsgImgRequest, UploadMsgImgResponse, UploadMsgImgRequest.Builder>
	{
		private const string TAG = "NetSceneUploadImage";
		public const int MM_MSGIMG_WITH_COMPRESS = 0;
		public const int MM_MSGIMG_WITHOUT_COMPRESS = 1;
		private const int ONE_2GPACK_UPLOADSIZE = 8192;
		private const int ONE_3GPACK_UPLOADSIZE = 16384;
		private const int ONE_WIFIPACK_UPLOADSIZE = 32768;
		public UpLoadImgContext mUpImgContext;
		private int mUpLoadedSize = 8192;
		private bool mIsNeedScale = true;
		public event onSceneFinishedDelegate mOnSceneFinished;
		public NetSceneUploadImage()
		{
			EventCenter.registerEventHandler(EventConst.ON_ACCOUNT_LOGIN, new EventHandlerDelegate(NetSceneUploadImage.onAccountLoginProc));
		}
		private static void onAccountLoginProc(EventWatcher watcher, BaseEventArgs evtArgs)
		{
			List<ChatMsg> list = StorageMgr.chatMsg.searhCacheMsg(3, 0, 1);
			List<ChatMsg> list2 = StorageMgr.chatMsg.searhCacheMsg(39, 0, 1);
			if (list2 != null && list2.get_Count() > 0)
			{
				if (list == null)
				{
					list = new List<ChatMsg>();
				}
				using (List<ChatMsg>.Enumerator enumerator = list2.GetEnumerator())
				{
					while (enumerator.MoveNext())
					{
						ChatMsg current = enumerator.get_Current();
						list.Add(current);
					}
				}
			}
			if (list != null && list.get_Count() > 0)
			{
				using (List<ChatMsg>.Enumerator enumerator2 = list.GetEnumerator())
				{
					while (enumerator2.MoveNext())
					{
						ChatMsg current2 = enumerator2.get_Current();
						current2.nStatus = 1;
					}
				}
				StorageMgr.chatMsg.updateMsgList(list);
				return;
			}
		}
		public ChatMsg doScene(string talkerName, string filename, Stream origStream, int msgType = 3, ParamEx param = null)
		{
			return new NetSceneUploadImage().doSceneEx(talkerName, filename, origStream, msgType, param);
		}
		public ChatMsg doScene(string talkerName, int nImgMsgTranId)
		{
			return new NetSceneUploadImage().doSceneEx(talkerName, nImgMsgTranId);
		}
		public ChatMsg doScene(string talkerName, string origImgPath, int msgType = 3)
		{
			if (!string.IsNullOrEmpty(talkerName) && !string.IsNullOrEmpty(origImgPath))
			{
				ChatMsg result;
				try
				{
					using (IsolatedStorageFile userStoreForApplication = IsolatedStorageFile.GetUserStoreForApplication())
					{
						if (!userStoreForApplication.FileExists(origImgPath))
						{
							result = null;
						}
						else
						{
							IsolatedStorageFileStream isolatedStorageFileStream = userStoreForApplication.OpenFile(origImgPath, 3, 1);
							if (isolatedStorageFileStream == null)
							{
								result = null;
							}
							else
							{
								result = this.doScene(talkerName, origImgPath, isolatedStorageFileStream, msgType, null);
							}
						}
					}
				}
				catch (Exception ex)
				{
					Log.smethod_1("NetSceneUploadImage", ex.get_Message());
					result = null;
				}
				return result;
			}
			return null;
		}
		private ChatMsg doSceneEx(string talkerName, string filename, Stream origStream, int msgType = 3, ParamEx param = null)
		{
			if (!string.IsNullOrEmpty(filename) && !string.IsNullOrEmpty(talkerName) && origStream != null)
			{
				try
				{
					this.mUpLoadedSize = this.getSendPackSize();
				}
				catch (Exception ex)
				{
					Log.smethod_1("NetSceneUploadImage", ex.ToString());
					this.mUpLoadedSize = 32768;
				}
				if (param != null)
				{
					this.mIsNeedScale = param.isNeedScale;
				}
				Log.smethod_4("NetSceneUploadImage", "==============startDoSence()");
				return UploadImgService.startDoSence(talkerName, filename, origStream, this, -1, msgType, param);
			}
			return null;
		}
		private ChatMsg doSceneEx(string talkerName, int nImgMsgTranId)
		{
			if (nImgMsgTranId > 0 && !string.IsNullOrEmpty(talkerName))
			{
				try
				{
					this.mUpLoadedSize = this.getSendPackSize();
				}
				catch (Exception ex)
				{
					Log.smethod_1("NetSceneUploadImage", ex.ToString());
					this.mUpLoadedSize = 32768;
				}
				return UploadImgService.startDoSence(talkerName, null, null, this, nImgMsgTranId, 3, null);
			}
			return null;
		}
		private byte[] readFromStream(IsolatedStorageFileStream fileStream, int startPos, int dataLen)
		{
			byte[] result;
			try
			{
				if (fileStream != null && (long)dataLen <= fileStream.get_Length())
				{
					byte[] array = new byte[dataLen];
					fileStream.Seek((long)startPos, 0);
					int num = fileStream.Read(array, 0, dataLen);
					if (num <= 0)
					{
						Log.smethod_1("NetSceneUploadImage", "read from stream lenght = " + num);
						result = null;
					}
					else
					{
						result = array;
					}
				}
				else
				{
					result = null;
				}
			}
			catch (Exception ex)
			{
				Log.smethod_1("NetSceneUploadImage", ex.get_Message());
				result = null;
			}
			return result;
		}
		public void doScene(UpLoadImgContext imgContext)
		{
			if (imgContext.mStatus != 0 && imgContext.mStatus != 4)
			{
				Log.smethod_1("NetSceneUploadImage", "doScene imgContext.mStatus error, status = " + imgContext.mStatus);
				return;
			}
			imgContext.mStatus = 1;
			this.mUpImgContext = imgContext;
			if (this.mUpImgContext == null || this.mUpImgContext.imgInfo == null || this.mUpImgContext.bigImageMemoryStream == null)
			{
				this.mUpImgContext.mStatus = 4;
				EventCenter.postEvent(EventConst.ON_NETSCENE_SENDIMG_FAIL, new ParamReturn(-1, this.mUpImgContext.imgInfo.nMsgLocalID, this.mUpImgContext.talkerName), null);
				this.doSceneFinished();
				return;
			}
			int num = this.mUpImgContext.imgInfo.nTotalDataLen - this.mUpImgContext.imgInfo.nTransDataLen;
			if (num != 0 && this.mUpImgContext.imgInfo.nTotalDataLen != 0)
			{
				Log.smethod_4("NetSceneUploadImage", "file size = " + this.mUpImgContext.imgInfo.nTotalDataLen + " byte");
				Account curAccount = AccountMgr.getCurAccount();
				this.mUpImgContext.imgInfo.strFromUserName = curAccount.strUsrName;
				int num2 = this.mUpImgContext.imgInfo.nTransDataLen * 100 / this.mUpImgContext.imgInfo.nTotalDataLen;
				if (num2 <= 5)
				{
					num2 = 5;
				}
				Log.smethod_4("NetSceneUploadImage", "Progress is: " + num2 + "%");
				EventCenter.postEvent(EventConst.ON_NETSCENE_SENDIMG_PROGRESS, new ParamReturn(num2, this.mUpImgContext.imgInfo.nMsgLocalID, this.mUpImgContext.talkerName), null);
				this.doScene();
				return;
			}
			Log.smethod_1("NetSceneUploadImage", "mUpImgContext send dataLen = 0 mUpImgContext.imgInfo.nMsgTransID = " + this.mUpImgContext.imgInfo.nMsgTransID);
			this.mUpImgContext.mStatus = 4;
			EventCenter.postEvent(EventConst.ON_NETSCENE_SENDIMG_FAIL, new ParamReturn(-1, this.mUpImgContext.imgInfo.nMsgLocalID, this.mUpImgContext.talkerName, this.mUpImgContext.imgInfo.strImagePath), null);
			this.doSceneFinished();
		}
		private void doScene()
		{
			int num = this.mUpImgContext.imgInfo.nTotalDataLen - this.mUpImgContext.imgInfo.nTransDataLen;
			if (num > this.mUpLoadedSize)
			{
				num = this.mUpLoadedSize;
			}
			if (string.IsNullOrEmpty(this.mUpImgContext.imgInfo.strFromUserName) || string.IsNullOrEmpty(this.mUpImgContext.imgInfo.strToUserName) || string.IsNullOrEmpty(this.mUpImgContext.imgInfo.strClientMsgId))
			{
				Log.smethod_1("NetSceneUploadImage", "Param error doScene fail");
				this.mUpImgContext.mStatus = 4;
				EventCenter.postEvent(EventConst.ON_NETSCENE_SENDIMG_FAIL, new ParamReturn(-1, this.mUpImgContext.imgInfo.nMsgTransID, this.mUpImgContext.talkerName), null);
				this.doSceneFinished();
				return;
			}
			byte[] array = new byte[num];
			this.mUpImgContext.bigImageMemoryStream.Seek((long)this.mUpImgContext.imgInfo.nTransDataLen, 0);
			this.mUpImgContext.bigImageMemoryStream.Read(array, 0, num);
			if (array == null)
			{
				Log.smethod_1("NetSceneUploadImage", "read buffer From Stream fail");
				this.mUpImgContext.mStatus = 4;
				EventCenter.postEvent(EventConst.ON_NETSCENE_SENDIMG_FAIL, new ParamReturn(-1, this.mUpImgContext.imgInfo.nMsgLocalID, this.mUpImgContext.talkerName), null);
				this.doSceneFinished();
				return;
			}
			base.beginBuilder();
			this.mBuilder.BaseRequest = NetSceneBase.makeBaseRequest(9);
			this.mBuilder.FromUserName = Util.toSKString(this.mUpImgContext.imgInfo.strFromUserName);
			this.mBuilder.ToUserName = Util.toSKString(this.mUpImgContext.imgInfo.strToUserName);
			this.mBuilder.ClientImgId = Util.toSKString(this.mUpImgContext.imgInfo.strClientMsgId);
			this.mBuilder.TotalLen = (uint)this.mUpImgContext.imgInfo.nTotalDataLen;
			this.mBuilder.StartPos = (uint)this.mUpImgContext.imgInfo.nTransDataLen;
			if (!this.mIsNeedScale)
			{
				this.mBuilder.CompressType = 1u;
			}
			else
			{
				this.mBuilder.CompressType = 0u;
			}
			this.mBuilder.DataLen = (uint)num;
			this.mBuilder.Data = Util.toSKBuffer(array);
			this.mBuilder.MsgType = (uint)this.mUpImgContext.mMsgType;
			this.mSessionPack.mCmdID = 9;
			this.mSessionPack.mNeedCompress = false;
			this.mSessionPack.mConnectMode = 2;
			base.endBuilder();
			this.mUpImgContext.mStatus = 2;
		}
		protected override void onFailed(UploadMsgImgRequest request, UploadMsgImgResponse response)
		{
			Log.smethod_1("NetSceneUploadImage", "Send image failed because of system error");
			this.mUpImgContext.mStatus = 4;
			EventCenter.postEvent(EventConst.ON_NETSCENE_SENDIMG_FAIL, new ParamReturn(-1, this.mUpImgContext.imgInfo.nMsgLocalID, this.mUpImgContext.talkerName), null);
			this.doSceneFinished();
		}
		protected override void onSuccess(UploadMsgImgRequest request, UploadMsgImgResponse response)
		{
			RetConst ret = (RetConst)response.BaseResponse.Ret;
			if (ret != RetConst.MM_OK)
			{
				if (ret == RetConst.MM_ERR_SYS)
				{
					int num = this.mUpImgContext.imgInfo.nTotalDataLen - this.mUpImgContext.imgInfo.nTransDataLen;
					if (num <= this.mUpLoadedSize)
					{
						this.mUpImgContext.mStatus = 5;
						this.mUpImgContext.imgInfo.nTransDataLen = this.mUpImgContext.imgInfo.nTotalDataLen;
						Log.smethod_4("NetSceneUploadImage", "Resend Complete!");
						EventCenter.postEvent(EventConst.ON_NETSCENE_SENDIMG_COMPLETE, new ParamReturn(100, this.mUpImgContext.imgInfo.nMsgTransID, this.mUpImgContext.talkerName), null);
						this.mUpImgContext.mStatus = 4;
						this.doSceneFinished();
						return;
					}
				}
				if (ret == RetConst.MM_ERR_NEED_QQPWD)
				{
					Log.smethod_4("NetSceneUploadImage", "send QQ IMG ERR_NEED_QQPWD");
					this.mUpImgContext.mStatus = 4;
					EventCenter.postEvent(EventConst.ON_NETSCENE_SENDIMG_FAIL, new ParamReturn(this.mUpImgContext.imgInfo.nMsgTransID, RetConst.MM_ERR_NEED_QQPWD), null);
					this.doSceneFinished();
					return;
				}
				Log.smethod_1("NetSceneUploadImage", "Send image failed because of net error ret = " + ret.ToString());
				this.mUpImgContext.mStatus = 4;
				EventCenter.postEvent(EventConst.ON_NETSCENE_SENDIMG_FAIL, new ParamReturn(-1, this.mUpImgContext.imgInfo.nMsgLocalID, this.mUpImgContext.talkerName), null);
				this.doSceneFinished();
				return;
			}
			else
			{
				uint arg_169_0 = response.StartPos;
				if (this.mUpImgContext.imgInfo.nTotalDataLen <= 0 || (ulong)response.StartPos > (ulong)((long)this.mUpImgContext.imgInfo.nTotalDataLen) || (ulong)response.StartPos < (ulong)((long)this.mUpImgContext.imgInfo.nTransDataLen) || (this.isUploadCompleted() && response.DataLen <= 0u))
				{
					Log.smethod_1("NetSceneUploadImage", "Send image failed because of response error");
					this.mUpImgContext.mStatus = 4;
					EventCenter.postEvent(EventConst.ON_NETSCENE_SENDIMG_FAIL, new ParamReturn(-1, this.mUpImgContext.imgInfo.nMsgLocalID, this.mUpImgContext.talkerName), null);
					this.doSceneFinished();
					return;
				}
				if (response.MsgId > 0u)
				{
					this.mUpImgContext.imgInfo.nMsgSvrID = (int)response.MsgId;
					this.mUpImgContext.chatMsgInfo.nMsgSvrID = (int)response.MsgId;
				}
				this.mUpImgContext.imgInfo.nTransDataLen = (int)response.StartPos;
				this.mUpImgContext.updateUploadImgContext(false);
				int num2 = this.mUpImgContext.imgInfo.nTransDataLen * 100 / this.mUpImgContext.imgInfo.nTotalDataLen;
				if (num2 <= 5)
				{
					num2 = 5;
				}
				EventCenter.postEvent(EventConst.ON_NETSCENE_SENDIMG_PROGRESS, new ParamReturn(num2, this.mUpImgContext.imgInfo.nMsgLocalID, this.mUpImgContext.talkerName), null);
				if (this.isUploadCompleted())
				{
					this.mUpImgContext.mStatus = 5;
					Log.smethod_4("NetSceneUploadImage", "send Complete!");
					EventCenter.postEvent(EventConst.ON_NETSCENE_SENDIMG_COMPLETE, new ParamReturn(num2, this.mUpImgContext.imgInfo.nMsgLocalID, this.mUpImgContext.talkerName), null);
					this.doSceneFinished();
					return;
				}
				this.doScene();
				return;
			}
		}
		private bool isUploadCompleted()
		{
			return this.mUpImgContext.imgInfo.nTransDataLen == this.mUpImgContext.imgInfo.nTotalDataLen && this.mUpImgContext.imgInfo.nTotalDataLen > 0;
		}
		public static int getProgress(int nMsgLocalID, string strToTalker)
		{
			int result = 0;
			int msgTransID = MsgTransStorageProxy.getMsgTransID(nMsgLocalID);
			if (msgTransID > 0)
			{
				MsgTrans byMsgTransID = StorageMgr.msgImg.getByMsgTransID(msgTransID);
				if (byMsgTransID != null)
				{
					result = byMsgTransID.nTransDataLen * 100 / byMsgTransID.nTotalDataLen;
				}
			}
			return result;
		}
		public void doSceneFinished()
		{
			if (this.mOnSceneFinished != null)
			{
				this.mOnSceneFinished(this.mUpImgContext);
			}
			this.mUpImgContext.updateUploadImgContext(true);
			this.mUpImgContext.bigImageMemoryStream.Close();
			this.mUpImgContext.bigImageMemoryStream.Dispose();
		}
		public int getSendPackSize()
		{
			if (NetworkDeviceWatcher.isCurrentWifi())
			{
				Log.smethod_4("NetSceneUploadImage", "Current net is Wifi");
				return 32768;
			}
			if (NetworkDeviceWatcher.isCurrentCell3G())
			{
				Log.smethod_4("NetSceneUploadImage", "Current net is 3G");
				return 16384;
			}
			if (NetworkDeviceWatcher.isCurrentCell2G())
			{
				Log.smethod_4("NetSceneUploadImage", "Current net is 2G");
				return 8192;
			}
			Log.smethod_4("NetSceneUploadImage", "Current net is UnKnow");
			return 16384;
		}
	}
}
